package com.snail.clouds.storage.providers.tianyi_tv;

import com.snail.clouds.storage.auth.LoginCredentials;
import com.snail.clouds.storage.auth.PersistentLoginInfo;
import com.snail.clouds.storage.core.AbstractStorageClient;
import com.snail.clouds.storage.entity.AccountInfo;
import com.snail.clouds.storage.entity.CloudFile;
import com.snail.clouds.storage.entity.TrashItem;
import com.snail.clouds.storage.exception.AuthException;
import com.snail.clouds.storage.exception.FileException;
import com.snail.clouds.storage.exception.CloudStorageException;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.function.BiConsumer;
import java.util.Date;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

/**
 * 天翼云TV版存储客户端实现
 */
public class TianyiTvClient implements AbstractStorageClient {
    
    private boolean loggedIn = false;
    private PersistentLoginInfo persistentInfo;
    private CloudsApi cloudsApi;
    
    // 登录相关
    private String accessToken;
    private String refreshToken;
    private String userId;
    private String username;
    private String familyId;
    private boolean isFamily = false;

    public TianyiTvClient() {
        this.cloudsApi = new CloudsApi();
    }

    @Override
    public boolean isLoggedIn() {
        return loggedIn;
    }

    @Override
    public String triggerLogin(LoginCredentials credentials) throws AuthException {
        try {
            this.username = credentials.getUsername();
            
            // 获取二维码UUID进行扫码登录
            Map<String, Object> uuidResult = cloudsApi.getQrCodeUUID();
            
            if (uuidResult == null || !uuidResult.containsKey("uuid")) {
                throw new AuthException("获取二维码失败");
            }
            
            String tempUuid = (String) uuidResult.get("uuid");
            return tempUuid; // 对于天翼TV，UUID本身就是会话标识符
            
        } catch (Exception e) {
            throw new AuthException("触发登录失败: " + e.getMessage(), e);
        }
    }

    @Override
    public PersistentLoginInfo checkLoginStatus(String sessionId) throws AuthException {
        try {
            // 检测二维码登录状态
            Map<String, Object> loginResult = cloudsApi.checkQrCodeLoginResult(sessionId);
            
            if (loginResult != null && loginResult.containsKey("accessToken")) {
                this.accessToken = (String) loginResult.get("accessToken");
                
                // 获取SessionKey和SessionSecret
                Map<String, Object> sessionResult = cloudsApi.loginFamilyMerge(this.accessToken);
                
                if (sessionResult == null) {
                    throw new AuthException("获取会话信息失败");
                }
                
                // 保存登录信息
                this.userId = (String) sessionResult.get("loginName");
                this.refreshToken = (String) sessionResult.get("refreshToken");
                
                // 设置API的token信息
                cloudsApi.setTokenInfo(sessionResult);
                
                // 设置登录状态
                this.loggedIn = true;
                
                return createPersistentInfo(sessionResult);
            }
            
            return null;
            
        } catch (Exception e) {
            throw new AuthException("检查登录状态失败: " + e.getMessage(), e);
        }
    }

    @Override
    public String serializeLoginInfo() throws AuthException {
        try {
            if (!loggedIn) {
                throw new AuthException("未登录，无法序列化登录信息");
            }
            
            // 构造登录信息字典
            Map<String, Object> loginInfo = new HashMap<String, Object>() {{
                put("access_token", accessToken);
                put("refresh_token", refreshToken);
                put("user_id", userId);
                put("username", username);
                put("logged_in", loggedIn);
                put("token_info", cloudsApi.getTokenInfo());
                put("family_id", familyId);
                put("is_family", isFamily);
                put("timestamp", new Date());
            }};
            
            // 序列化为JSON字符串
            return JSONUtil.toJsonStr(loginInfo);
            
        } catch (Exception e) {
            throw new AuthException("序列化登录信息失败: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean restoreLoginFromString(String serializedInfo) throws AuthException {
        try {
            // 反序列化登录信息
            Map<String, Object> loginInfo = JSONUtil.toBean(serializedInfo, Map.class);
            
            // 恢复登录状态
            this.accessToken = (String) loginInfo.get("access_token");
            this.refreshToken = (String) loginInfo.get("refresh_token");
            this.userId = (String) loginInfo.get("user_id");
            this.username = (String) loginInfo.get("username");
            this.loggedIn = (Boolean) loginInfo.getOrDefault("logged_in", false);
            this.familyId = (String) loginInfo.get("family_id");
            this.isFamily = (Boolean) loginInfo.getOrDefault("is_family", false);
            
            // 设置API的token信息
            cloudsApi.setTokenInfo((Map<String, Object>) loginInfo.get("token_info"));
            cloudsApi.setFamilyId(this.familyId);
            cloudsApi.setFamily(this.isFamily);
            
            // 验证token是否有效
            if (!validateToken()) {
                this.loggedIn = false;
                throw new AuthException("Token已过期，请重新登录");
            }
            
            return true;
            
        } catch (Exception e) {
            this.loggedIn = false;
            throw new AuthException("恢复登录状态失败: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean refreshToken() throws AuthException {
        try {
            if (!loggedIn) {
                throw new AuthException("未登录");
            }
            
            // 调用API的refreshSession方法刷新会话
            boolean success = cloudsApi.refreshSession();
            
            if (!success) {
                throw new AuthException("刷新会话失败");
            }
            
            return true;
            
        } catch (Exception e) {
            throw new AuthException("刷新访问令牌失败: " + e.getMessage(), e);
        }
    }

    @Override
    public AccountInfo getAccountInfo() throws AuthException, CloudStorageException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            // 获取用户信息
            Map<String, Object> userInfo = cloudsApi.getUserInfo();
            
            if (userInfo == null) {
                throw new CloudStorageException("获取用户信息失败");
            }
            
            // 从用户信息中提取容量信息
            long totalSpace = 0;
            long usedSpace = 0;
            
            // 根据Go语言实现，处理容量信息
            if (userInfo.containsKey("cloudCapacityInfo")) {
                Map<String, Object> capacityInfo = (Map<String, Object>) userInfo.get("cloudCapacityInfo");
                totalSpace = ((Number) capacityInfo.getOrDefault("totalSize", 0)).longValue();
                usedSpace = ((Number) capacityInfo.getOrDefault("usedSize", 0)).longValue();
            } else if (userInfo.containsKey("familyCapacityInfo")) {
                Map<String, Object> capacityInfo = (Map<String, Object>) userInfo.get("familyCapacityInfo");
                totalSpace = ((Number) capacityInfo.getOrDefault("totalSize", 0)).longValue();
                usedSpace = ((Number) capacityInfo.getOrDefault("usedSize", 0)).longValue();
            }
            
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setUserId((String) userInfo.getOrDefault("loginName", ""));
            accountInfo.setUsername((String) userInfo.getOrDefault("loginName", ""));
            accountInfo.setTotalSpace(totalSpace);
            accountInfo.setUsedSpace(usedSpace);
            
            return accountInfo;
            
        } catch (Exception e) {
            throw new CloudStorageException("获取账户信息失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<CloudFile> listFiles(String folderId) throws AuthException, FileException, CloudStorageException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            folderId = folderId != null ? folderId : "-11"; // 根目录
            List<Map<String, Object>> filesData = cloudsApi.getFiles(folderId);
            
            List<CloudFile> files = new ArrayList<>();
            for (Map<String, Object> item : filesData) {
                CloudFile cloudFile = new CloudFile();
                cloudFile.setId((String) item.getOrDefault("id", ""));
                cloudFile.setName((String) item.getOrDefault("name", ""));
                cloudFile.setSize(((Number) item.getOrDefault("size", 0)).longValue());
                cloudFile.setDirectory((Boolean) item.getOrDefault("isFolder", false));
                cloudFile.setParentId((String) item.get("parentId"));
                
                // 处理时间字段
                String createDate = (String) item.get("createDate");
                String lastOpTime = (String) item.get("lastOpTime");
                if (StrUtil.isNotBlank(createDate)) {
                    cloudFile.setCreateTime(SignatureUtils.parseTimeString(createDate));
                }
                if (StrUtil.isNotBlank(lastOpTime)) {
                    cloudFile.setUpdateTime(SignatureUtils.parseTimeString(lastOpTime));
                }
                
                cloudFile.setMd5((String) item.get("md5"));
                
                // 处理预览URL
                if (item.containsKey("smallUrl")) {
                    cloudFile.setSmallUrl((String) item.get("smallUrl"));
                }
                if (item.containsKey("largeUrl")) {
                    cloudFile.setLargeUrl((String) item.get("largeUrl"));
                }
                
                files.add(cloudFile);
            }
            
            return files;
            
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().toLowerCase().contains("not found")) {
                throw new FileException("文件夹不存在: " + folderId, e);
            }
            throw new CloudStorageException("列出文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public CloudFile createFolder(String name, String parentId) throws AuthException, FileException, CloudStorageException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            parentId = parentId != null ? parentId : "-11"; // 根目录
            Map<String, Object> folderData = cloudsApi.createFolder(name, parentId);
            
            CloudFile cloudFile = new CloudFile();
            cloudFile.setId((String) folderData.getOrDefault("id", ""));
            cloudFile.setName((String) folderData.getOrDefault("name", name));
            cloudFile.setSize(0);
            cloudFile.setDirectory(true);
            cloudFile.setParentId(parentId);
            
            // 处理时间字段
            String createDate = (String) folderData.get("createDate");
            String lastOpTime = (String) folderData.get("lastOpTime");
            if (StrUtil.isNotBlank(createDate)) {
                cloudFile.setCreateTime(SignatureUtils.parseTimeString(createDate));
            }
            if (StrUtil.isNotBlank(lastOpTime)) {
                cloudFile.setUpdateTime(SignatureUtils.parseTimeString(lastOpTime));
            }
            
            return cloudFile;
            
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().toLowerCase().contains("not found")) {
                throw new FileException("父文件夹不存在: " + parentId, e);
            }
            throw new CloudStorageException("创建文件夹失败: " + e.getMessage(), e);
        }
    }

    @Override
    public CloudFile uploadFile(String fileName, byte[] fileData, String parentId, boolean overwrite, BiConsumer<Integer, Integer> progressCallback) throws AuthException, FileException, CloudStorageException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            parentId = parentId != null ? parentId : "-11"; // 根目录
            
            // 计算文件MD5
            String fileMd5 = cn.hutool.crypto.digest.DigestUtil.md5Hex(fileData);
            String fileSize = String.valueOf(fileData.length);
            
            // 创建上传会话
            Map<String, Object> uploadInfo = cloudsApi.createUploadFile(parentId, fileMd5, fileName, fileSize);
            
            // 检查文件是否已存在（秒传）
            if (uploadInfo.containsKey("fileDataExists") && (Integer)uploadInfo.get("fileDataExists") == 1) {
                // 文件已存在，直接提交
                Map<String, Object> commitResult = cloudsApi.commitUploadFile(
                    (String) uploadInfo.get("fileCommitUrl"),
                    (Long) uploadInfo.get("uploadFileId"),
                    overwrite
                );
                
                return convertToCloudFile(commitResult, fileName, parentId);
            }
            
            // 需要上传文件
            long uploadFileId = (Long) uploadInfo.get("uploadFileId");
            String uploadUrl = (String) uploadInfo.get("fileUploadUrl");
            
            // 分块上传文件
            int chunkSize = 1024 * 1024; // 1MB
            long totalSize = fileData.length;
            long uploadedSize = 0;
            
            while (uploadedSize < totalSize) {
                int chunkLength = (int) Math.min(chunkSize, totalSize - uploadedSize);
                byte[] chunk = new byte[chunkLength];
                System.arraycopy(fileData, (int) uploadedSize, chunk, 0, chunkLength);
                
                // 上传分块
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Range", "bytes " + uploadedSize + "-" + (uploadedSize + chunkLength - 1) + "/" + totalSize);
                headers.put("ResumePolicy", "1");
                
                if (isFamily) {
                    headers.put("FamilyId", familyId);
                    headers.put("UploadFileId", String.valueOf(uploadFileId));
                } else {
                    headers.put("Edrive-UploadFileId", String.valueOf(uploadFileId));
                }
                
                HttpUtils.put(uploadUrl, headers, chunk);
                
                uploadedSize += chunkLength;
                
                // 更新进度
                if (progressCallback != null) {
                    int progress = (int) (uploadedSize * 100 / totalSize);
                    progressCallback.accept(progress, 100);
                }
            }
            
            // 提交上传
            Map<String, Object> commitResult = cloudsApi.commitUploadFile(
                (String) uploadInfo.get("fileCommitUrl"),
                uploadFileId,
                overwrite
            );
            
            return convertToCloudFile(commitResult, fileName, parentId);
            
        } catch (Exception e) {
            throw new CloudStorageException("上传文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void deleteFile(String fileId) throws AuthException, FileException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            // 创建删除任务
            List<Map<String, Object>> taskInfos = new ArrayList<>();
            
            // 获取文件信息以判断是否为文件夹
            CloudFile file = getFileInfo(fileId, null);
            if (file == null) {
                throw new FileException("文件不存在: " + fileId);
            }
            
            Map<String, Object> taskInfo = new HashMap<>();
            taskInfo.put("fileId", fileId);
            taskInfo.put("fileName", file.getName());
            taskInfo.put("isFolder", SignatureUtils.boolToNumber(file.isDirectory()));
            taskInfos.add(taskInfo);
            
            // 创建批量删除任务
            Map<String, Object> taskResult = cloudsApi.createBatchTask("DELETE",
                isFamily ? familyId : "", null, null, taskInfos);
            
            String taskId = (String) taskResult.get("taskId");
            
            // 等待任务完成
            boolean completed = false;
            int retryCount = 0;
            int maxRetries = 30; // 最多等待30秒
            
            while (!completed && retryCount < maxRetries) {
                Map<String, Object> status = cloudsApi.checkBatchTask("DELETE", taskId);
                int taskStatus = (Integer) status.get("taskStatus");
                
                if (taskStatus == 4) { // 完成
                    completed = true;
                } else if (taskStatus == 2) { // 冲突
                    throw new FileException("删除文件冲突: " + fileId);
                }
                
                if (!completed) {
                    Thread.sleep(1000); // 等待1秒
                    retryCount++;
                }
            }
            
            if (!completed) {
                throw new FileException("删除文件超时: " + fileId);
            }
            
        } catch (Exception e) {
            throw new FileException("删除文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public CloudFile moveFile(String fileId, String newParentId, String folderId) throws AuthException, FileException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            // 获取文件信息
            CloudFile file = getFileInfo(fileId, folderId);
            if (file == null) {
                throw new FileException("文件不存在: " + fileId);
            }
            
            // 创建移动任务
            List<Map<String, Object>> taskInfos = new ArrayList<>();
            
            Map<String, Object> taskInfo = new HashMap<>();
            taskInfo.put("fileId", fileId);
            taskInfo.put("fileName", file.getName());
            taskInfo.put("isFolder", SignatureUtils.boolToNumber(file.isDirectory()));
            taskInfos.add(taskInfo);
            
            // 创建批量移动任务
            Map<String, Object> taskResult = cloudsApi.createBatchTask("MOVE",
                isFamily ? familyId : "", newParentId, null, taskInfos);
            
            String taskId = (String) taskResult.get("taskId");
            
            // 等待任务完成
            boolean completed = false;
            int retryCount = 0;
            int maxRetries = 30; // 最多等待30秒
            
            while (!completed && retryCount < maxRetries) {
                Map<String, Object> status = cloudsApi.checkBatchTask("MOVE", taskId);
                int taskStatus = (Integer) status.get("taskStatus");
                
                if (taskStatus == 4) { // 完成
                    completed = true;
                } else if (taskStatus == 2) { // 冲突
                    throw new FileException("移动文件冲突: " + fileId);
                }
                
                if (!completed) {
                    Thread.sleep(1000); // 等待1秒
                    retryCount++;
                }
            }
            
            if (!completed) {
                throw new FileException("移动文件超时: " + fileId);
            }
            
            // 更新文件信息
            file.setParentId(newParentId);
            return file;
            
        } catch (Exception e) {
            throw new FileException("移动文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public CloudFile renameFile(String fileId, String newName) throws AuthException, FileException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            // 获取文件信息
            CloudFile file = getFileInfo(fileId, null);
            if (file == null) {
                throw new FileException("文件不存在: " + fileId);
            }
            
            // 调用重命名API
            Map<String, Object> result = cloudsApi.renameFile(fileId, newName, file.isDirectory());
            
            // 更新文件信息
            file.setName(newName);
            file.setUpdateTime(SignatureUtils.parseTimeString((String) result.get("lastOpTime")));
            
            return file;
            
        } catch (Exception e) {
            throw new FileException("重命名文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public CloudFile getFileInfo(String fileId, String folderId) throws AuthException, FileException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            // 通过列出文件夹内容来查找文件
            String searchFolderId = folderId != null ? folderId : "-11";
            List<Map<String, Object>> files = cloudsApi.getFiles(searchFolderId);
            
            for (Map<String, Object> file : files) {
                if (fileId.equals(file.get("id"))) {
                    return convertToCloudFile(file, (String) file.get("name"),
                        (String) file.get("parentId"));
                }
            }
            
            throw new FileException("文件不存在: " + fileId);
            
        } catch (Exception e) {
            throw new FileException("获取文件信息失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<CloudFile> searchFiles(String parentId, String query) throws AuthException, CloudStorageException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            // 天翼TV没有专门的搜索API，这里简化实现
            // 通过列出文件夹内容并过滤来实现搜索
            String searchFolderId = parentId != null ? parentId : "-11";
            List<Map<String, Object>> allFiles = cloudsApi.getFiles(searchFolderId);
            
            List<CloudFile> result = new ArrayList<>();
            
            for (Map<String, Object> file : allFiles) {
                String fileName = (String) file.get("name");
                if (fileName != null && fileName.toLowerCase().contains(query.toLowerCase())) {
                    result.add(convertToCloudFile(file, fileName, (String) file.get("parentId")));
                }
            }
            
            return result;
            
        } catch (Exception e) {
            throw new CloudStorageException("搜索文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<TrashItem> listTrash() throws AuthException {
        // 天翼TV暂不支持回收站功能
        throw new UnsupportedOperationException("天翼TV暂不支持回收站功能");
    }

    @Override
    public void emptyTrash() throws AuthException {
        // 天翼TV暂不支持回收站功能
        throw new UnsupportedOperationException("天翼TV暂不支持回收站功能");
    }

    @Override
    public String getDownloadUrl(String fileId) throws AuthException, FileException, CloudStorageException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            String downloadUrl = cloudsApi.getDownloadUrl(fileId);
            
            if (StrUtil.isBlank(downloadUrl)) {
                throw new FileException("文件不存在: " + fileId);
            }
            
            return downloadUrl;
            
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().toLowerCase().contains("not found")) {
                throw new FileException("文件不存在: " + fileId, e);
            }
            throw new CloudStorageException("获取下载链接失败: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean checkFastUpload(String fileName, byte[] fileData) throws AuthException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            String parentId = "-11"; // 默认根目录
            
            // 计算文件MD5
            String fileMd5 = cn.hutool.crypto.digest.DigestUtil.md5Hex(fileData);
            String fileSize = String.valueOf(fileData.length);
            
            // 创建上传会话检查文件是否已存在
            Map<String, Object> uploadInfo = cloudsApi.createUploadFile(parentId, fileMd5, fileName, fileSize);
            
            // 检查文件是否已存在（秒传）
            return uploadInfo.containsKey("fileDataExists") && (Integer)uploadInfo.get("fileDataExists") == 1;
            
        } catch (Exception e) {
            throw new AuthException("检查快速上传失败: " + e.getMessage(), e);
        }
    }

    @Override
    public CloudFile fastUploadFile(String fileName, byte[] fileData, String parentId) throws AuthException, FileException, CloudStorageException {
        if (!loggedIn) {
            throw new AuthException("未登录");
        }
        
        try {
            parentId = parentId != null ? parentId : "-11"; // 根目录
            
            // 计算文件MD5
            String fileMd5 = cn.hutool.crypto.digest.DigestUtil.md5Hex(fileData);
            String fileSize = String.valueOf(fileData.length);
            
            // 创建上传会话
            Map<String, Object> uploadInfo = cloudsApi.createUploadFile(parentId, fileMd5, fileName, fileSize);
            
            // 检查文件是否已存在（秒传）
            if (uploadInfo.containsKey("fileDataExists") && (Integer)uploadInfo.get("fileDataExists") == 1) {
                // 文件已存在，直接提交
                Map<String, Object> commitResult = cloudsApi.commitUploadFile(
                    (String) uploadInfo.get("fileCommitUrl"),
                    (Long) uploadInfo.get("uploadFileId"),
                    true
                );
                
                return convertToCloudFile(commitResult, fileName, parentId);
            } else {
                throw new CloudStorageException("文件不存在，无法快速上传");
            }
            
        } catch (Exception e) {
            throw new CloudStorageException("快速上传文件失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 验证当前token是否有效
     */
    private boolean validateToken() {
        try {
            // 尝试获取用户信息来验证token
            cloudsApi.getUserInfo();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 创建持久化登录信息
     */
    private PersistentLoginInfo createPersistentInfo(Map<String, Object> loginData) {
        PersistentLoginInfo info = new PersistentLoginInfo();
        info.setAccessToken((String) loginData.getOrDefault("accessToken", ""));
        info.setRefreshToken((String) loginData.getOrDefault("refreshToken", ""));
        // 简化处理，实际应该解析expiresAt字段
        info.setExpireTime(System.currentTimeMillis() + 24 * 60 * 60 * 1000); // 默认24小时后过期
        return info;
    }
    
    /**
     * 将API返回的文件信息转换为CloudFile对象
     */
    private CloudFile convertToCloudFile(Map<String, Object> fileData, String fileName, String parentId) {
        CloudFile cloudFile = new CloudFile();
        cloudFile.setId((String) fileData.getOrDefault("id", ""));
        cloudFile.setName((String) fileData.getOrDefault("name", fileName));
        cloudFile.setSize(((Number) fileData.getOrDefault("size", 0)).longValue());
        cloudFile.setDirectory(false); // 默认为文件，由调用方设置
        cloudFile.setParentId(parentId);
        cloudFile.setMd5((String) fileData.get("md5"));
        
        // 处理时间字段
        String createDate = (String) fileData.get("createDate");
        String lastOpTime = (String) fileData.get("lastOpTime");
        if (StrUtil.isNotBlank(createDate)) {
            cloudFile.setCreateTime(SignatureUtils.parseTimeString(createDate));
        }
        if (StrUtil.isNotBlank(lastOpTime)) {
            cloudFile.setUpdateTime(SignatureUtils.parseTimeString(lastOpTime));
        }
        
        // 处理预览URL
        if (fileData.containsKey("smallUrl")) {
            cloudFile.setSmallUrl((String) fileData.get("smallUrl"));
        }
        if (fileData.containsKey("largeUrl")) {
            cloudFile.setLargeUrl((String) fileData.get("largeUrl"));
        }
        
        return cloudFile;
    }
    
    /**
     * 解析时间戳
     */
    // 移除parseTimestamp方法，使用Utils.parseTimeString替代
    
    /**
     * 设置家庭云模式
     */
    public void setFamilyMode(boolean isFamily, String familyId) {
        this.isFamily = isFamily;
        this.familyId = familyId;
        cloudsApi.setFamily(isFamily);
        cloudsApi.setFamilyId(familyId);
    }
}